<template>
  <el-dialog
    :title="title"
    :visible.sync="isVisible"
    :width="width"
    :before-close="handleClose"
    :lock-scroll="true"
    :close-on-click-modal="false"
    custom-class="pub_dialog"
    @open="getData"
  >
    <VForm
      ref="vformComponents"
      :form="formData.form"
      :options="formData.options"
      :rules="formData.rules"
      :labelWidth="formData.labelWidth"
      :rowspan="rowspan"
      @toLoadMethods="toLoadMethods"
    ></VForm>

    <div class="formTitle-root" v-show="paramValueList.length>0">
      <div class="form-title-p">实时监测值</div>
    </div>
    <div v-show="paramValueList.length>0">
      <el-table :data="paramValueList" border>
        <el-table-column prop="itemName" label="监测项">
          <template slot-scope="scope">
            <div>{{ scope.row.itemName }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="itemValue" label="监测值">
          <template slot-scope="scope">
            <el-input
              type="text"
              v-model="scope.row.itemValue"
              :disabled="openType=='detail'"
              placeholder="监测值"
            ></el-input>
            <!--<div v-else>{{ scope.row.itemValue }}</div>-->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="sure" v-if="openType!='detail'">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  alarmRealHistoryDetail,
  alarmRealHistoryUpdate,
  alarmRealHistoryAdd
} from '@/api/alarm/history'
import {
  alarmDeviceList,
  queryDeviceItem
} from '@/api/alarm/device'
import VForm from "@/components/VForm";

export default {
  components: {
    VForm,
  },
  props: {
    width: {
      type: String,
      default: "70%",
    },
    title: {
      type: String,
      default: "详情",
    },
    id: {},
    openType: {
      type: String,
      default: "add"
    },
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    'width': {
      handler(newVal, oldVal) {
        console.log('newVal===', newVal, oldVal)
        let w = this.width.split('%')[0]
        if (w >= 60) {
          this.rowspan = 2
        } else {
          this.rowspan = 1
        }
      },
      deep: true,
      immediate: true
    },
    'modeType': {
      handler(newVal, oldVal) {
        this.formData.form.modeType = newVal;
      },
      deep: true,
      immediate: true
    },
    // 'equipmentTypeOptions': {
    //   handler(newVal, oldVal) {
    //     this.formData.options.forEach(t => {
    //       if (t.key == 'equipmentType') {
    //         t.option.data = newVal
    //       }
    //     })
    //   },
    //   deep: true,
    //   immediate: true
    // },
    // 'deviceTypeOptions': {
    //   handler(newVal, oldVal) {
    //     this.formData.options.forEach(t => {
    //       if (t.key == 'deviceType') {
    //         t.option.data = newVal
    //       }
    //     })
    //   },
    //   deep: true,
    //   immediate: true
    // },
    // 'monitorTypeOptions': {
    //   handler(newVal, oldVal) {
    //     this.formData.options.forEach(t => {
    //       if (t.key == 'monitorType') {
    //         t.option.data = newVal
    //       }
    //     })
    //   },
    //   deep: true,
    //   immediate: true
    // },
    'eventTypeOptions': {
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'eventType') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'alarmDeviceList':{
      handler(newVal, oldVal) {
        this.formData.options.forEach(t => {
          if (t.key == 'deviceId') {
            t.option.data = newVal
          }
        })
      },
      deep: true,
      immediate: true
    },
    'openType':{
      handler(newVal, oldVal) {
        this.formData.options = this.formData.options.filter(t=> !t.readonly)
        if(newVal != 'add'){
          let item = {
            title: "标识码",
            key: "identificationCode",
            type: "text",
            disabled: true,
            readonly:true
          }
          this.formData.options.unshift(item)
        }
        this.formData.options.forEach(t => {
          if(!t.readOnly){
            if(t.key=='deviceId')
              t.disabled =  newVal == 'detail'
          }
        })
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    isVisible: {
      get() {
        return this.dialogVisible
      },
      set() {
        this.close()
      }
    }
  },
  data() {
    return {
      paramValueList:[],
      modeType: '',
      rowspan: 1,
      dict: {},
      formData: {
        form: {
          modeType: this.modeType,
          identificationCode: "",
          deviceId: "",
          deviceCode: "",
          equipmentType: "",
          deviceName: "",
          deviceType: "",
          monitorType: "",
          facilityId: "",
          facilityName: "",
          ponitId: "",
          pointName: "",
          eventId: "",
          eventKey: "",
          eventType: "",
          paramValueList: "",
        },
        options: [
          // {
          //   title: "标识码",
          //   key: "identificationCode",
          //   type: "text",
          // },
          /*{
            title: "设备id",
            key: "deviceId",
            type: "text",
          },*/
          {
            title: "设备名称",
            key: "deviceId",
            type: "select",
            event: 'changeAlarmDevice',
            option: {
              data: this.alarmDeviceList,
              props: {
                key: "id", // 指定key对应data的字段
                label: "name", // 指定label对应data的字段
                value: "id", // 指定value对应data的字段
              },
            },
          },
          {
            title: "设备代码",
            key: "deviceCode",
            type: "text",
            multiple: false,
            event: 'changeAlarmDevice',
            option: {
              data: this.alarmDeviceList,
              props: {
                key: "id", // 指定key对应data的字段
                label: "name", // 指定label对应data的字段
                value: "deviceCode", // 指定value对应data的字段
              },
            },
            disabled: true,
            placeholder:"选择设备自动获取"
          },
          {
            title: "设备型号",
            key: "equipmentType",
            type: "text",
            disabled: true,
            placeholder:"选择设备自动获取"
          },
          {
            title: "设备类型",
            key: "deviceType",
            type: "text",
            disabled: true,
            placeholder:"选择设备自动获取"
          },
          {
            title: "设备监测类型",
            key: "monitorType",
            type: "text",
            disabled: true,
            placeholder:"选择设备自动获取"
          },
          /*{
            title: "设施id",
            key: "facilityId",
            type: "text",
          },*/
          {
            title: "设施名称",
            key: "facilityName",
            type: "text",
            disabled: true,
            placeholder:"选择设备自动获取"
          },
          /*{
            title: "监测点位id",
            key: "ponitId",
            type: "text",
          },*/
          {
            title: "监测点位名称",
            key: "pointName",
            type: "text",
            disabled: true,
            placeholder:"选择设备自动获取"
          },
          /**
          {
            title: "事件ID",
            key: "eventId",
            type: "text",
          },
          {
            title: "事件Key",
            key: "eventKey",
            type: "text",
          },
          {
            title: "事件类型",
            key: "eventType",
            // type: "select",
            // multiple: false,
            // option: {
            //   data: this.eventTypeOptions,
            //   props: {
            //     key: "id", // 指定key对应data的字段
            //     label: "label", // 指定label对应data的字段
            //     value: "value", // 指定value对应data的字段
            //   },
            // },
            type: "text",
          },
          */
          // {
          //   title: "监测项值",
          //   key: "paramValueList",
          //   type: "text",
          // }
        ],
        rules: {
          modeType: [
            {required: true, message: '请选择', trigger: 'change'},
          ],
          // identificationCode: [
          //   {max: 20, message: '长度最大为20个字符', trigger: 'blur'}
          // ],
          deviceId: [],
          deviceCode: [
            {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
          ],
          equipmentType: [],
          deviceName: [
            {max: 128, message: '长度最大为128个字符', trigger: 'blur'}
          ],
          deviceType: [],
          monitorType: [],
          facilityId: [],
          facilityName: [
            {max: 128, message: '长度最大为128个字符', trigger: 'blur'}
          ],
          ponitId: [],
          pointName: [
            {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
          ],
          eventId: [
            {max: 64, message: '长度最大为64个字符', trigger: 'blur'}
          ],
          eventKey: [
            {max: 32, message: '长度最大为32个字符', trigger: 'blur'}
          ],
          eventType: [],
          paramValueList: [
            {max: 1024, message: '长度最大为1024个字符', trigger: 'blur'}
          ],
        },
        labelWidth: "140px",
      },
      // 字典
      modeTypeOptions: [],
      // equipmentTypeOptions: [],
      // deviceTypeOptions: [],
      // monitorTypeOptions: [],
      eventTypeOptions: [],
      alarmDeviceList:[],
    };
  },
  methods: {
    toLoadMethods(methods) {
      this[methods]()
    },
    changeAlarmDevice(){
     let item =  this.alarmDeviceList.find(t=>t.id==this.formData.form.deviceId)
      if(item!=undefined){
        console.log("item ====>",item)
        // 赋值
        queryDeviceItem({deviceId:item.id}).then(res=>{
          if(res.code==200){
              let data =res.data
              this.formData.form.deviceCode = data.deviceCode
              this.formData.form.equipmentType = data.equipmentType
              this.formData.form.deviceName = data.name
              this.formData.form.deviceType =data.typeName
              this.formData.form.monitorType = data.monitorTypeName
              this.formData.form.facilityName = data.facilityName
              this.formData.form.facilityId = data.facilityId
              this.formData.form.pointName =  data.monitorObjectName
              this.formData.form.ponitId = data.monitorId
              this.formData.form.facilityId =  data. facilityId
              this.paramValueList = data.deviceItems.map(t=>{
                return {itemId:t.id,itemName:t.name,itemValue:""}
              })
          }
        })
      }
    },
    submitFormat() {
      this.formData.form.paramValueList = JSON.stringify(this.paramValueList)
    },
    loadFormat() {
      this.paramValueList = this.formData.form.paramValueList!=null ?
          JSON.parse(this.formData.form.paramValueList) :[]
    },
    getCheckBoxData(value, option, type) {
      if (type == "submit") {
        if (value.length == 0) {
          return null
        }
        let temp = [];
        value.forEach(t => {
          let item = option.find(x => x.label == t)
          if (item != undefined) {
            temp.push(item.value)
          }
        })
        return temp.join(",")
      } else {
        if (!value) {
          return []
        } else {
          let data = value.split(",")
          let temp = []
          data.forEach(t => {
            let item = option.find(x => x.value == t)
            if (item != undefined) {
              temp.push(item.label)
            }
          })
          return temp
        }
      }
    },
    sure() {
      // this.formData.form.identificationCode="1"
      console.log('sure===', this.formData.form)
      this.$refs.vformComponents.$refs.form.validate().then(res => {
        this.submitFormat()
        if (this.openType == "add") {
          this.add()
        } else {
          this.update()
        }
      })
    },
    add() {
      this.formData.form.id = null
      alarmRealHistoryAdd(this.formData.form).then(res => {
        if (res.code == 200) {
          this.$message({
            message: this.$t('tips.createSuccess'),
            type: 'success'
          })
          this.closeSuccess()
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      })
    },
    update() {
      alarmRealHistoryUpdate(this.formData.form).then(res => {
        if (res.code == 200) {
          this.$message({
            message: this.$t('tips.updateSuccess'),
            type: 'success'
          })
          this.closeSuccess()
        } else {
          this.$message({
            message: this.$t('tips.systemException'),
            type: 'error'
          })
        }
      })
    },
    cancel() {
      this.close()
    },
    handleClose(done) {
      done()
      this.close()
    },
    closeSuccess() {
      this.$refs.vformComponents.$refs.form.resetFields();
      this.$emit('success')
    },
    close() {
      this.$refs.vformComponents.$refs.form.resetFields();
      this.$emit('close')
    },
    getData() {
      this.paramValueList = []
      if (this.openType != "add") {
        alarmRealHistoryDetail(this.id).then(res => {
          if (res.code == 200) {
            this.formData.form = res.data
            this.loadFormat()
          } else {
            this.$message({
              message: this.$t('tips.systemException'),
              type: 'error'
            })
          }
        })
      }
    },
    getAlarmDeviceList(){
      let param = {
         modeType: this.modeType,
         delFlag: 0
      }
      alarmDeviceList(param).then(res=>{
        if(res.code==200){
          this.alarmDeviceList = res.data
        }
      })
    },
    initAlarmConfig() {
      let type = this.$route.path
      console.log("path:" + type)
      const config = this.$commonJs.getAlarmPathConfig(this.$route.path)
      this.modeType = config.modeTypeSs
      this.getAlarmDeviceList()
    }
  },
  created() {
    this.initAlarmConfig()
  }
};
</script>

<style lang="scss" scoped>
  @import "@/styles/element-variables.scss";
  .formTitle-root{
    padding: 10px 0;
    border-bottom: 1px solid #EFEFEF;
    font-size: 16px;
    position: relative;
    margin-bottom: 10px;
    .form-title-p{
      padding-left: 10px;
      border-left: 4px solid $--color-primary;
    }
  }
  /* 2023.10.12 禁用转态样式修改 ----------------开始------------------------- */
  ::v-deep .is-disabled .el-input__inner  {
    background-color:white;
    /*color: rgb(0, 0, 0);*/
  }
  ::v-deep .el-radio__input.is-disabled.is-checked .el-radio__inner{
    border-color: $--color-primary;
    background: $--color-primary;
  }
  ::v-deep .el-radio__input.is-disabled + span.el-radio__label{
    color: rgb(0, 0, 0);
  }
  ::v-deep .el-textarea.is-disabled .el-textarea__inner{
    background: white;
    color: rgb(0, 0, 0);
  }
  /* 2023.10.12 禁用转态样式修改 ----------------结束------------------------- */
</style>
